export default {
    namespaced: true,
    state: {
        yxUrl: 'https://api.it120.cc/small4',//严选商城url地址
        historyList: [],//模糊搜索历史纪录页面

        token: '',
        user: {},
        cartList: [],//存储购物车的数据
    },
    mutations: {
        //添加历史纪录
        addHistory(state, name) {
            console.log(name);
            if (state.historyList.length >= 8) {
                state.historyList.pop();
            }
            state.historyList.unshift(name);
        },
        //删除历史纪录
        removeHistory(state, index = 0) {
            state.historyList = [];
        },

        //用户登录的操作
        doLogin(state, data) {
            console.log(data);
            state.user = data;
            state.token = data.token;
        },

        logout(state) {
            state.user = {};
            state.token = "";
        },

        addCart(state, goods) {
            let index = state.cartList.findIndex(item => {
                return item.id == goods.id;
            })
            console.log(index);
            if (index > -1) {
                state.cartList[index].num += goods.num;
            } else {
                //加入购物车的数据操作
                state.cartList.push(goods);
            }
            console.log(goods);

        }
    },

    getters: {
        //统计加入购物车商品总数量
        nums(state) {
            console.log('dssddsds');
            let num = 0;
            state.cartList.forEach(item => {
                if (item.checkd == true) {
                    num += item.num;
                }
            })
            console.log(num);

            return num;
        },

        totals(state) {

            return state.cartList.reduce((pre, item) => {
                if (item.checkd == true) {
                    pre += item.num * item.price;
                }
                return pre;
            }, 0);
        }
    }
}